﻿using Core.IRepository;
using Core.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Core.Service
{
    public class BaseService<T> where T : BaseModel, new()
    {
        public IBaseRepository baseRepostory;
        public IUnitOfWork unitOfWork;

        public BaseService(IBaseRepository repostory, IUnitOfWork unitOfWork)
        {
            this.baseRepostory = repostory;
            this.unitOfWork = unitOfWork;
        }


        public async Task<int> AddAsync(T obj)
        {
            baseRepostory.Add<T>(obj);
            return await unitOfWork.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(int id)
        {
            baseRepostory.Delete<T>(id);
            return await unitOfWork.SaveChangesAsync();
        }

        public async Task<int> EditAsync(T obj)
        {
            baseRepostory.Update<T>(obj);
            return await unitOfWork.SaveChangesAsync();
        }

        public async Task<T> GetEnityAsync(Expression<Func<T, bool>> expression)
        {
            return await baseRepostory.Find(expression).FirstOrDefaultAsync();
        }

        //public IQueryable<T> GetList()
        //{
        //    if (expression == null)
        //        expression = t => true;
        //    return baseRepostory.Find(expression);
        //}

        public IQueryable<T> GetList(Expression<Func<T, bool>> expression = null)
        {
            if (expression == null)
                expression = t => true;
            return baseRepostory.Find(expression);
        }

        public IQueryable<T> GetList<TOrder>(Expression<Func<T, bool>> expression, int pageSize, int pageIndex, out int total, Expression<Func<T,TOrder>> order,bool IsAsc=true)
        {
            return baseRepostory.Find<T, TOrder>(pageIndex, pageSize, expression, order, out total, IsAsc);
        }
    }
}
